<template>
  <div class="app-container">
    <div  v-if="!detailVisible">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-select v-model="queryParams.deviceName" placeholder="请选择设备名称" clearable style="width: 200px">
          <el-option
              v-for="dict in device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备SN" prop="deviceSn">
        <el-input
          v-model="queryParams.deviceSn"
          placeholder="请输入设备SN"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备ID" prop="sensorId">
        <el-input
            v-model="queryParams.sensorId"
            placeholder="请输入设备ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['device:deviceInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:deviceInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:deviceInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['device:deviceInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table scrollbar-always-on v-loading="loading" :data="deviceInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" fixed="left" align="center" prop="deviceName" width="200px">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.deviceName"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="监测点编号" fixed="left" align="center" prop="monitorId" width="240px">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="monitorIds" :value="scope.row.monitorId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="供应商" align="center" prop="sensorBrand" />
      <el-table-column label="设备型号" align="center" prop="sensorModel" width="110px"/>
      <el-table-column label="设备ID" align="center" prop="sensorId" width="110px"/>
      <el-table-column label="设备SN" align="center" prop="deviceSn" width="100px"/>
      <el-table-column label="固件版本号" align="center" prop="firmwareVersion" width="120px"/>
      <el-table-column label="通讯状态" align="center" prop="commStatus" width="120px">
        <template #default="scope">
          <dict-tag :options="sensor_data_status" :value="scope.row.commStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="数据状态" align="center" prop="dataStatus" width="120px">
        <template #default="scope">
          <dict-tag :options="slope_data_status" :value="scope.row.dataStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="接入协议" align="center" prop="protocol" />
      <el-table-column label="物联网卡ICCID" align="center" prop="iccid" width="200"/>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width"  width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:deviceInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['device:deviceInfo:remove']">删除</el-button>
          <el-button link type="primary" icon="Operation" @click="handleDetails(scope.row)" v-hasPermi="['deviceInfo:deviceInfo:list']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deviceInfoRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-select v-model="form.deviceName" placeholder="请选择设备名称">
            <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监测点编号" prop="slopeCode">
          <el-select v-model="form.monitorId" placeholder="请选择监测点编号">
            <el-option
                v-for="dict in monitorIds"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="sensorBrand">
          <el-input v-model="form.sensorBrand" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="设备型号" prop="sensorModel">
          <el-input v-model="form.sensorModel" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备ID" prop="sensorId">
          <el-input v-model="form.sensorId" placeholder="请输入设备ID" />
        </el-form-item>
        <el-form-item label="设备SN" prop="deviceSn">
          <el-input v-model="form.deviceSn" placeholder="请输入设备SN" />
        </el-form-item>
        <el-form-item label="固件版本号" prop="firmwareVersion">
          <el-input v-model="form.firmwareVersion" placeholder="请输入固件版本号" />
        </el-form-item>
        <el-form-item label="接入协议" prop="protocol">
          <el-input v-model="form.protocol" placeholder="请输入接入协议" />
        </el-form-item>
        <el-form-item label="物联网卡ICCID" prop="iccid">
          <el-input v-model="form.iccid" placeholder="请输入物联网卡ICCID" />
        </el-form-item>
        <el-form-item label="管养单位" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择管养单位">
            <el-option
              v-for="dict in sys_dept_list"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div v-if="detailVisible" class="detail-container">
    <div class="detail-header">
      <el-button @click="returnback">返回列表</el-button>
    </div>

    <el-tabs v-model="activeTab"  @tab-click="handleTabClick">
      <el-tab-pane
          v-for="tab in tabs"
          :key="tab.value"
          :label="tab.name"
          :name="tab.value"
      />
    </el-tabs>

    <div class="detail-content">
      <!--        <component :is="activeTab" :device="currentDevice" />-->
      <!--        <DataView :device="currentDevice" />-->
      <!--        <{{ activeTab }} :device="currentDevice" />-->
      <!--        <DataView></DataView>-->

      <DataView1 v-if="activeTab === 'DataView1'" :deviceSn="currentDevice.deviceSn" />
      <DeviceDetail1 v-if="activeTab === 'DeviceDetail1'" :device="currentDevice" />
      <CommandHistory1 v-if="activeTab === 'CommandHistory1'" :device="currentDevice" />
      <DeviceStatus1 v-if="activeTab === 'DeviceStatus1'" :device="currentDevice" />
      <ConnectionLog1 v-if="activeTab === 'ConnectionLog1'" :device="currentDevice" />
      <ErrorLog1 v-if="activeTab === 'ErrorLog1'" :device="currentDevice" />
    </div>
  </div>
  </div>
</template>

<script setup name="DeviceInfo">
import { listDeviceInfo, getDeviceInfo, delDeviceInfo, addDeviceInfo, updateDeviceInfo } from "@/api/slope/device/deviceInfo/deviceInfo.js";
import DeviceStatus1 from "@/views/slope/data/DeviceStatus.vue";
import DataView1 from "@/views/slope/data/DataView.vue";
import DeviceDetail1 from "@/views/slope/data/DeviceDetail.vue";
import ErrorLog1 from "@/views/slope/data/ErrorLog.vue";
import ConnectionLog1 from "@/views/slope/data/ConnectionLog.vue";
import CommandHistory1 from "@/views/slope/data/CommandHistory.vue";
import {listMonitorPoints} from "@/api/slope/monitorPoints/monitorpoints.js";

const { proxy } = getCurrentInstance();
const { sys_dept_list,device_type, sensor_data_status, slope_data_status } = proxy.useDict('sys_dept_list','device_type', 'sensor_data_status', 'slope_data_status');

const monitorIds = ref([])
const deviceInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentDevice = ref({});// 当前设备详情数据
const activeTab = ref('DataView1'); // 确保这里的值是正确的组件名称 // 当前激活的tab
const detailVisible = ref(false); // 控制详情页显示
// 选项卡配置（可扩展）
const tabs = [
  { name: '查看数据', value: 'DataView1' },
  { name: '设备详情', value: 'DeviceDetail1' },
  { name: '下发历史', value: 'CommandHistory1' },
  { name: '设备状态', value: 'DeviceStatus1' },
  { name: '连接日志', value: 'ConnectionLog1' },
  { name: '异常日志', value: 'ErrorLog1' }
]
function handleTabClick(tab, event) {
  // 打印当前点击的标签页的数据
  activeTab.value = tab.props.name; // 更新当前激活的标签页
}

function handleDetails(row) {
  getDeviceInfo(row.deviceSn).then(res => {
    currentDevice.value = row; // 确保这里正确获取并赋值
    detailVisible.value = true;    // 显示详情页
    activeTab.value = 'DataView1';  // 默认激活 DataView 选项卡
  }).catch(err => {
    proxy.$modal.msgError("获取设备详情失败");
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName:"",
    deviceSn: null,
    sensorId:null,
  },
  rules: {
    deviceName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
    monitorId: [
      { required: true, message: "所属监测点不能为空", trigger: "blur" }
    ],
    deviceSn: [
      { required: true, message: "设备SN不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "管养单位不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备列表列表 */
function getList() {
  loading.value = true;
  listMonitorPoints().then(response => {
    monitorIds.value = Object.entries(response).map(([key, value]) => ({
      label: key,
      value: value
    }))
  })
  listDeviceInfo(queryParams.value).then(response => {
    deviceInfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deviceName: null,
    monitorId: null,
    sensorBrand: null,
    sensorModel: null,
    sensorId: null,
    deviceSn: null,
    firmwareVersion: null,
    commStatus: null,
    dataStatus: null,
    protocol: null,
    iccid: null,
    deptId: null,
    updateTime: null
  };
  proxy.resetForm("deviceInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备列表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDeviceInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备列表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDeviceInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDeviceInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备列表编号为"' + _ids + '"的数据项？').then(function() {
    return delDeviceInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/deviceInfo/export', {
    ...queryParams.value
  }, `deviceInfo_${new Date().getTime()}.xlsx`)
}

function returnback(){
  detailVisible.value=false;
}
getList();
</script>
